package com.yqg.education.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yqg.education.entity.UserRole;
import com.yqg.education.mapper.UserRoleMapper;
import com.yqg.education.service.IUserRoleService;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.ArrayList;
import java.util.List;

/**
 * UserRoleServiceImpl 服务实现类
 * @author zxf
 * @since 2025-03-01
 */
@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements IUserRoleService {

    @Override
    public boolean updateUserRole(List<Long> checkedId) {
        //先删除原数据表中与该user_id相同的role_id
        Long userId = checkedId.get(checkedId.size() - 1);
        deleteByUserId(userId);
        checkedId.remove(checkedId.size() - 1);

        ArrayList<UserRole> userRoles = new ArrayList<>();

        for (int i = 0; i < checkedId.size(); i++) {
            //向数据库中存
            UserRole userRole = new UserRole();
            //设置user_id
            userRole.setUserId(userId);
            userRole.setRoleId(Long.valueOf(checkedId.get(i)));
            userRoles.add(userRole);
        }
        return saveBatch(userRoles);
    }

    /**
     * 通过userId删除
     */
    public void deleteByUserId(@PathVariable Long userId) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("user_id", userId);
        remove(qw);
    }
}
